<?php

	/**
	 *            ________ ___
	 *           /   /   /\  /\       Konsolidate
	 *      ____/   /___/  \/  \
	 *     /           /\      /      http://konsolidate.klof.net
	 *    /___     ___/  \    /
	 *    \  /   /\   \  /    \       Class:  CoreDevMediaVideoFLV
	 *     \/___/  \___\/      \      Tier:   CoreDev
	 *      \   \  /\   \  /\  /      Module: Media/Video/FLV
	 *       \___\/  \___\/  \/
	 *         \          \  /        $Rev: 0 $
	 *          \___    ___\/         $Author: john $
	 *              \   \  /          $Date: 2007-08-12 13:58:57 +0200 (Sun, 12 Aug 2007) $
	 *               \___\/
	 */
	class CoreDevMediaVideoFLV extends Konsolidate
	{

		public $uploaddir;
		public $resource;
		private $watermark;
		private $generated;
		private $_ffmpegbin;
		
		public function __construct( $oParent )
		{
			parent::__construct( $oParent );
			$this->uploaddir = $this->get( '/Config/path/upload' );
			$this->watermark = $this->get( '/Config/path/flvlogo', false );
			$this->_ffmpegbin= $this->get( '/Config/ffmpeg/bin');
		}


		/**
		 *  Convert resource to flv
		 *  @name    convert
		 *  @type    method
		 *  @access  public
		 *  @param   string resource
		 *  @returns string token
		 *  @syntax  Object->convert( string resource )
		 */
		public function convert( $sResource, $iWidth = 320, $iHeight = 240 )
		{
			$this->resource = $sResource;
			$this->generated = "{$sResource}.flv";

			$sCommand = $this->_ffmpegbin . " -i " . escapeshellarg($this->uploaddir . '/' . $sResource) . " -ar 22050 -ab 32 {$this->getWatermark()} -f flv -s " . intval( $iWidth ) . "x" . intval( $iHeight ) . " -aspect 4:3 -map_meta_data " .
						escapeshellarg($this->uploaddir . '/' . $sResource . ':' . $this->uploaddir . '/' . $sResource . '.flv') .
						" -y " . escapeshellarg( $this->uploaddir . '/' . $this->generated );

			shell_exec( $sCommand );

			return file_exists( "{$this->uploaddir}/{$this->generated}" ) ? "{$this->uploaddir}/{$this->generated}" : "";
		}


		/**
		 *  Abort convert of resource to flv
		 *  @name    abort
		 *  @type    method
		 *  @access  public
		 *  @param   string token
		 *  @returns boolean
		 *  @syntax  Object->abort( string token )
		 */
		public function abort( $sToken )
		{
			return true;
		}


		/**
		 *  Get watermark from (external) resource
		 *  @name    getWatermark
		 *  @type    method
		 *  @access  private
		 *  @param   string resource uri (gif)
		 *  @param   boolean unique watermark
		 *  @returns string ffmpeg watermark command or empty
		 *  @syntax  this->getWatermark( string token )
		 */
		private function getWatermark( $bUnique = false )
		{
			if ( $this->watermark == false )
				return '';

			$sCommand = " -vhook '" . $this->get('/Config/ffmpeg/watermarklib') . " -f %s' ";
			$sDestinationFile = !$bUnique ? $this->watermark : "{$this->uploaddir}/{$this->generated}_watermark.gif";

			if ( !$bUnique && file_exists( $sDestinationFile ) )
				return sprintf( $sCommand, $sDestinationFile );

			if ( $bUnique )
				$this->removeWatermark( $sDestinationFile );

			$mResource = $this->call('/Media/Image/load', $this->watermark);
			$mDestination = $this->call('/Media/Image/load', $sDestinationFile);

			return sprintf( $sCommand, $sDestinationFile );
		}


		/**
		 *  Remove watermark on service media
		 *  @name    removeWatermark
		 *  @type    method
		 *  @access  private
		 *  @param   string resource
		 *  @returns boolean
		 *  @syntax  this->removeWatermark( string resource )
		 */
		private function removeWatermark( $sResource )
		{
			return file_exists( $sResource ) && unlink( $sResource );
		}


		/**
		 *  Get status of convert of resource to flv
		 *  @name    getstatus
		 *  @type    method
		 *  @access  public
		 *  @param   string token
		 *  @returns string
		 *  @syntax  Object->getStatus( string token )
		 */
		public function getStatus( $sToken )
		{
			$oRs = $this->call( "/DB/query", "SELECT flvstatus FROM flashvideo WHERE flvtoken=" . $this->call( "/DB/quote", $sToken ) );

			return $oRow = $oRs->next() ? $oRow->flvstatus : '';
		}


		/**
		 *  Get duration of generated flv
		 *  @name    getDuration
		 *  @type    method
		 *  @access  public
		 *  @returns int (miliseconds)
		 *  @syntax  Object->getDuration()
		 */
		public function getDuration()
		{
			$iDuration = -1;

			if ( file_exists( "{$this->uploaddir}/{$this->generated}" ) )
			{
				$fh = fopen( "{$this->uploaddir}/{$this->generated}", "r" );
				$sContents = fread( $fh, filesize( "{$this->uploaddir}/{$this->generated}" ) );
				fclose( $fh );

				if ( strlen( $sContents ) > 3 &&  substr( $sContents, 0, 3 ) == "FLV" )
				{
					$sTaglen = hexdec( bin2hex( substr( $sContents, strlen( $sContents ) -3 ) ) );
					if ( strlen( $sContents ) > $sTaglen )
						$iDuration = hexdec( bin2hex( substr( $sContents, strlen( $sContents ) - $sTaglen,3 ) ) );
				}
			}

			return $iDuration;
		}


		/**
		 *  Create screenshot
		 *  @name    createScreenshot
		 *  @type    method
		 *  @access  public
		 *  @param   video resource
		 *  @param   int pixel width
		 *  @param   int pixel height
		 *  @param   int position (seconds)
		 *  @param   image resource (or null to create a new image)
		 *  @param   string type (png or jpeg)
		 *  @returns resource image
		 *  @syntax  Object->createScreenshot( resource image [, int width [, int height [, int position [, mixed image [, string type]]]]] )
		 */
		public function createScreenshot( $sResource, $iWidth=120, $iHeight=90, $iPosition=null, $mImage=null, $sType='jpg' )
		{
			$sScreenshotUri = "{$this->uploaddir}/{$sResource}.{$sType}";

			switch( $sType )
			{
				case 'png' : 	$sOptions = '-f rawvideo -vcodec png ';
								break;

				case 'jpg' :
				default : 		$sOptions = '-f mjpeg ';
								$sType = 'jpg';
								break;
			}

			if ( is_null( $iPosition ) )
				$iPosition = $this->getDuration() >= 0 ? .5 * $this->getDuration() * .001 : 0;

			$sCommand = $this->_ffmpegbin . " -ss {$iPosition} -i " .
						escapeshellarg( $this->uploaddir . '/' . $sResource ) .
						" -s {$iWidth}x{$iHeight} -vframes 1 {$sOptions} -y " .
						escapeshellarg( $sScreenshotUri );

			shell_exec( $sCommand );

			if ( file_exists( "{$sScreenshotUri}" ) )
				return $sScreenshotUri;

			return false;
		}
	}

?>